﻿
using AppMachine.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using System.Reflection;

namespace AppMachine.EntityFrameworkCore;

public class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext> {
    //private readonly string _dbConnectionString = $"F:/AA.工作/AA.SourceCode/AA.Framework.IndustryControl/AppData/AppData.db";
    private readonly string _dbConnectionString = $"{new FileInfo(Assembly.GetExecutingAssembly().Location).Directory}/AppData/AppData.db";
    public AppDbContext CreateDbContext(string[] args) {
        if (!File.Exists(this._dbConnectionString)) {
            // 如果数据库文件不存在，则创建文件夹以确保路径存在
            var tempDirDB = Path.GetDirectoryName(this._dbConnectionString);
            if (!string.IsNullOrEmpty(tempDirDB) && !Directory.Exists(tempDirDB)) {
                Directory.CreateDirectory(tempDirDB);
            }
        }

        var builder = new DbContextOptionsBuilder<AppDbContext>()
            .UseSqlite($"Data Source={this._dbConnectionString}");

        return new AppDbContext(builder.Options);
    }

}
